package LeetCode;

import java.util.LinkedList;

/**
 * @Author：DijaH
 * @Date：2023/4/2 5:23 下午
 * @Version：1.0.0
 * @Description： 实现一个加减计算器
 *
 */
public class code224_calculate {
    public static int calculate(String exp) {
        return value(exp.replaceAll(" " ,"").toCharArray(),0)[0];
    }

    public static int[] value(char[] str,int i){
        LinkedList<String> que = new LinkedList<>();
        int cur = 0;
        int[] bra = null;
        while(i < str.length && str[i] != ')'){
            //如果当前位置是数字
            if(str[i] >= '0' && str[i] <= '9'){
                cur = cur * 10 + str[i++] - '0';
            }else if(str[i] != '('){
                //到这里说明遇到了运算符，那么就做计算
                addNum(que,cur);
                //入队
                que.addLast(String.valueOf(str[i++]));
                cur = 0;
            }else{
                //如果遇到左括号,那么就看看下一个数字
                bra = value(str,i + 1);
                cur = bra[0];
                i = bra[1] + 1;
            }
        }
        addNum(que,cur);
        return new int[]{getNum(que),i};
    }

    public static int getNum(LinkedList<String> que){
        int res = 0;
        boolean add = true;
        String cur = null;
        int num = 0;
        while(!que.isEmpty()){
            cur = que.pollFirst();
            if(cur.equals("+")){
                add = true;
            }else if(cur.equals("-")){
                add = false;
            }else{
                num = Integer.valueOf(cur);
                res += add ? num : (-num);
            }
        }
        return res;
    }

    public static void addNum(LinkedList<String> que,int num){
        if(!que.isEmpty()){
            int cur = 0;
            String top = que.pollLast();
            if(top.equals("+") || top.equals("-")){
                que.addLast(top);
            }else{
                //乘除
                cur = Integer.valueOf(que.pollLast());
                num = top.equals("*") ? (cur * num) : (cur / num);
            }
        }
        que.addLast(String.valueOf(num));
    }

    public static void main(String[] args) {
        String exp = "1+2+(1+2)";
        int calculate = calculate(exp);
        System.out.println(calculate);
    }
}
